package org.example.mallchat.service.impl;

import org.example.mallchat.common.service.RedissonServiceUtils;
import org.example.mallchat.dao.UserBackpackDao;
import org.example.mallchat.domain.entity.UserBackpack;
import org.example.mallchat.domain.enums.IdempotentEnum;
import org.example.mallchat.service.iservice.ItemService;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: zzh
 * @date: 2024/12/23 21:41:05
 * @version: 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private UserBackpackDao userBackpackDao;

    @Resource
    private RedissonServiceUtils redissonServiceUtils;

    @Override
    public void acquireItemToUser(Long toUserId, Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        // 先获取唯一Idempotent的标识！
        String idempotentKey = getIdempotentKey(itemId, idempotentEnum, businessId);
        try {
            redissonServiceUtils.executeWithLock(idempotentKey,()->{
                UserBackpack userBackpack = userBackpackDao.getBackpackByIdempotent(idempotentKey);
                if (userBackpack != null) {
                    // 已经存在，直接返回,避免重复操作！
                    return null;
                }
                // 不存在
                userBackpack = new UserBackpack();
                userBackpack.setUid(toUserId);
                userBackpack.setItemId(itemId);
                userBackpack.setIdempotent(idempotentKey);
                userBackpack.setStatus(0);
                userBackpackDao.save(userBackpack);
                return null;
            });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    // 幂等号=itemId+source+businessId
    private String getIdempotentKey(Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        return String.format("%d_%d_%s", itemId, idempotentEnum.getType(), businessId);
    }
}
